"""
基于python的yield 和 yield from的特性 实现异步效果
关键词：
    事件驱动/时间循环
"""

import time
from functools import partial

scheduled_list = []
timeout_list = []


class Future(object):

    def __init__(self):
        self.callbacks = []
        self.value = None

    def add_callback(self, callback):
        self.callbacks.append(callback)

    def set_done(self, value):
        self.value = value
        for callback in self.callbacks:
            callback()

    def get_result(self):
        return self.value


class Timeout(object):

    def __init__(self, timeout, callback):
        self.deadline = time.time() + timeout
        self.callback = callback

    def call(self):
        self.callback(None)


def sleep(sec):
    future = Future()
    timeout = Timeout(sec, future.set_done)
    timeout_list.append(timeout)
    yield future


def fun(sec):
    print('start')
    if sec:
        yield from sleep(sec)
    print('end')


def loop(*coroutines):
    scheduled_list.extend(Handle(c) for c in coroutines)

    while True:
        deadline = time.time()
        for timeout in timeout_list[:]:
            if timeout.deadline <= deadline:
                timeout.call()
                timeout_list.remove(timeout)

        while scheduled_list:
            handle = scheduled_list.pop(0)
            handle.call()

        if not scheduled_list and not timeout_list:
            break


async def a_test():
    return


if __name__ == "__main__":
    loop(fun(2), fun(2), fun(0))


